# -*- coding: utf-8 -*-
import gtk
import hildon
import gtkhtml2
import sys
from cesta import cesta

class kalorie:
    
    kalk_w = file(cesta+"/kalorie/kalk.txt", "a")
    kalk_r = file(cesta+"/kalorie/kalk.txt", "r").read()
    
    def zobraz_seznam(self):
        database = file(cesta+"/kalorie/vyhledavani/vyhled.dat", "r");
        r = database.read();
        
        cary = 0
        nazev = ""
        kj = ""
        mezi = []
        

        for i in r:
            rep = i
            if rep == "\t":
                rep = " "
                cary = cary + 1
  
            if cary == 0:
                nazev = nazev + rep
            elif cary == 1:
                kj = kj + rep
    
            if rep == "\n":
                kalk = []
                
                mezi.append(nazev)
                             
                cary = 0
                nazev = ""
                kj = ""
        
        selector = hildon.TouchSelectorEntry(text = True);
        
        for polozka in range(len(mezi)):
            selector.append_text(mezi[polozka]);
            
        return selector;
    
    def pridat_potravinu(self, widget, win):
        database = file(cesta+"/kalorie/vyhledavani/vyhled.dat", "r");
        r = database.read();
        
        cary = 0
        nazev = ""
        kj = ""
        mezi = []
        kalk = []
        

        for i in range(len(r)):
            rep = r[i]
            if rep == "\t":
                rep = " "
                cary = cary + 1
  
            if cary == 0:
                nazev = nazev + rep
            elif cary == 1:
                kj = kj + rep
    
            if rep == "\n":
                kalk = []
                
                kalk.append(nazev)
                kalk.append(kj)
                mezi.append(kalk)
                             
                cary = 0
                nazev = ""
                kj = ""

        kalorie.kalk = mezi
        self.pridej_selector(None, mezi)
        win.destroy()
        self.kalkulacka()
                
    
    def on_page_switch_odeb(self, notebook, page, num, dialog, selector, kalk):
        print >>sys.stderr, "Page %d" % num;
        
        if num == 2:
            select = selector.get_selected_rows(0)[0][0];
            

            kalk.pop(select);
                
            kalorie.kalk_w = file(cesta+"/kalorie/kalk.txt", "w")
            kalorie.kalk_w.write(str(kalk))
            kalorie.kalk_w.flush()
            kalorie.kalk_r = file(cesta+"/kalorie/kalk.txt", "r").read()

                
    def smaz_kalk_potr(self, widget, win, kalk):

        notebook = gtk.Notebook()
        
        label_1 = gtk.Label("V nasledujicim kroku vyberte potravinu\nkterou chcete odebrat");
        label_2 = gtk.Label("Potravina byla uspesne odebrana");
        
        notebook.append_page(label_1, None)
        
        selector = hildon.TouchSelectorEntry(text = True);
        
        for polozka in range(len(kalk)):
            selector.append_text(kalk[polozka][0]);
        
        notebook.append_page(selector, None);
        notebook.append_page(label_2, None);
        
        dialog = hildon.WizardDialog(None, "Vyberte potravinu kterou chcete odebrat", notebook)
        
        notebook.connect("switch-page", self.on_page_switch_odeb, dialog, selector, kalk)

        
        dialog.show_all();
        dialog.run();
        dialog.destroy();
        win.destroy();
        self.kalkulacka();
        
    
    def smaz_kalk(self, widget, win):
        kalorie.kalk_w = file(cesta+"/kalorie/kalk.txt", "w")
        kalorie.kalk_w.flush()
        kalorie.kalk_r = file(cesta+"/kalorie/kalk.txt", "r").read()
        win.destroy()
        self.kalkulacka()

    def kalkulacka(self, widget = None):
        win3 = hildon.StackableWindow();
        win3.set_title("Kalkulacka kalorii");
        vb = gtk.VBox()
        
        menu = hildon.AppMenu();
        
        pridb= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Pridat potravinu");
        pridb.connect("clicked", self.pridat_potravinu, win3);
        menu.append(pridb)
        
        pannableArea = hildon.PannableArea()
        
        
        if kalorie.kalk_r == "" or kalorie.kalk_r == "[]":
            mezi = "Nejdriv musite pridat nejakou potravinu"
            view = gtk.Label(mezi)
        else:
            kalk_r_l = eval(kalorie.kalk_r)
        
            mezi = "<html><body><table border='1'><tr><td>Nazev</td><td>KJ</td></tr><tr><td></td><td></td></tr>"
            soucet = 0
            view = gtkhtml2.View()
            document = gtkhtml2.Document()
            view.set_document(document)


            for i in range(len(kalk_r_l)):
                mezi = mezi + "<tr><td>" + kalk_r_l[i][0] + "</td><td>" + kalk_r_l[i][1] + "</td></tr>"
                soucet = soucet + int(kalk_r_l[i][1])
            
            mezi = mezi + "<tr><td></td><td></td></tr>" + "<tr><td>" + "Soucet" + "</td><td>" + str(soucet) + "</td></tr>" + "</body></html>"
            document.open_stream("text/html")
            document.write_stream(mezi)
            
            
            vympotb= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Smazat potravinu");
            vympotb.connect("clicked", self.smaz_kalk_potr, win3, kalk_r_l);
            menu.append(vympotb)
            
            vymb= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Smazat");
            vymb.connect("clicked", self.smaz_kalk, win3);
            menu.append(vymb)
        
        pannableArea.add(view)
        label = gtk.Label(mezi)
        vb.pack_start(pannableArea, True)
        
        menu.show_all()
        win3.set_app_menu(menu)
        win3.add(vb)
        win3.show_all()
        

    def on_page_switch_prid(self, notebook, page, num, dialog, selector):
        print >>sys.stderr, "Page %d" % num;
        
        if num == 2:
            select = selector.get_selected_rows(0)[0][0];
            selectn = []
            
            print >>sys.stderr, select;
            
            selectn.append(kalorie.kalk[select]);
            
            
            
            selectns = str(selectn)
            
            if kalorie.kalk_r == "":
                kalorie.kalk_w = file(cesta+"/kalorie/kalk.txt", "w")
                kalorie.kalk_w.write(selectns)
                kalorie.kalk_w.flush()
                kalorie.kalk_r = file(cesta+"/kalorie/kalk.txt", "r").read()
            else:
                kalorie.kalk_w = file(cesta+"/kalorie/kalk.txt", "w")
                kalorie.kalk_w.write(str(eval(kalorie.kalk_r) + selectn))
                kalorie.kalk_w.flush()
                kalorie.kalk_r = file(cesta+"/kalorie/kalk.txt", "r").read()

                 

    def pridej_selector(self, widget, kalk):

        notebook = gtk.Notebook()
        
        label_1 = gtk.Label("V nasledujicim kroku vyberte potravinu\nkterou chcete pridat do seznamu");
        label_2 = gtk.Label("Potravina byli uspesne pridana");
        
        notebook.append_page(label_1, None)
        
        selector = hildon.TouchSelectorEntry(text = True);
        
        for polozka in range(len(kalk)):
            selector.append_text(kalk[polozka][0]);
            
        
        notebook.append_page(selector, None);
        notebook.append_page(label_2, None);
        
        dialog = hildon.WizardDialog(None, "Vyberte potravinu kterou chcete pridat", notebook)
        
        notebook.connect("switch-page", self.on_page_switch_prid, dialog, selector)

        
        dialog.show_all();
        dialog.run();
        dialog.destroy() 
        
    
    def nuluj(self, widget, entry):
        entry.set_text("");   
    
    def vyhlkalgui(self, widget):
    
        otevreno_nebez=0;
    
        win = hildon.StackableWindow();
        win.set_title("Zadejte jmeno potraviny");
    
    
        selector = self.zobraz_seznam()
    
        b = hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Zobraz!");
        b.connect("clicked", self.vyhlkal, selector, win);
    
        #nuluj_entry= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Vynulovat");
        #nuluj_entry.connect("clicked", self.nuluj, entry);
        
        #navod_label = gtk.Label("Prvni pismeno v nazvu musi byt velke.\nNazvy piste bez hacku a carek.\nNapriklad: Banany, Madeta, Yoplait")

    
    
        vb = gtk.VBox();
        hb = gtk.HBox();
        win.add(vb);
        vb.pack_start(selector, expand=True);
        vb.pack_start(hb, expand=False);
       # vb.pack_start(navod_label)
        hb.pack_start(b, expand=True);
       #hb.pack_start(nuluj_entry, expand=False);
    

        
        win.show_all();
    
    def vyhlkal(self, widget, selector, win):
        hledano = selector.get_entry().get_text() #nacteni hledaneho textu z entry
        kalorie.hledano = hledano
    
        database = file(cesta+"/kalorie/vyhledavani/vyhled.dat", "r"); 
        r = database.read();
        
    
        index = r.find(hledano);
        if index == -1 or kalorie.hledano == " " or  kalorie.hledano == "":
            banner=hildon.hildon_banner_show_information(win,"None" , "Zadana potravina neni v databazi!");
            banner.set_timeout(3000);
            return
        
        
        
        pocet = 0
        indexs=[]
        indexs.append(index)
        
        while index != -1:   #hledani postupne v celem souboru
            pocet += 1; 
            start = index + 3;  
            index = r.find(hledano, start);
            indexs.append(index)
            
        
        indexs.append(-1) #pridani -1 do seznamu vysledku vyhledavani abych poznal konec seznamu

        win1=hildon.StackableWindow();
        
        nazev = "";   #inicializace promnenych ktere poziju pro pridavani do kalkulacky
        kj = "";
        
        kalorie.kalk = [];
        
        
        kde = 0
        rep = indexs[kde] + 1;
        
        if indexs[kde] == -1:    #pokud se nic nevyhledalo tak zobraz upozorneni
            banner=hildon.hildon_banner_show_information(win,"None" , "Potravina neni v databazi!");
            banner.set_timeout(3000);
            database.close()
        else:                   #nebo zacni spracovavat text
            kalorie.mezi = "";
            cary = 0;
            kalorie.rep1 = "";

            #Prehozeni vysledku vyhledavani na zacatek radku
            while indexs[kde]!=-1:
                rep = rep - 1;
                kalorie.rep1 = r[rep];
                
                if kalorie.rep1 == "\n":
                    indexs[kde] = rep + 1;
                    kde = kde + 1;
                    rep = indexs[kde] + 1;
                    continue
                
            kde = 0;
            rep = indexs[kde];
            
            
            #Spracovani textu
            while indexs[kde]!=-1:    
              
                if rep == indexs[kde]:
                    kalorie.mezi = kalorie.mezi + "Nazev: ";
                
                kalorie.rep1 = r[rep];
            

                rep = rep + 1;
      
                if kalorie.rep1 == "\t":
                        cary = cary+1;
                        kalorie.rep1="";
                        if cary == 1:
                            kalorie.mezi = kalorie.mezi + "\nEnergie: ";
                        
                        if cary == 2:
                            kalorie.mezi = kalorie.mezi + "\nBilkoviny: ";

                
                        elif cary==3:
                            kalorie.mezi = kalorie.mezi + "\nTuky: ";

                        elif cary==4:
                            kalorie.mezi = kalorie.mezi + "\nSacharidy: ";
            
                        elif cary==5:
                            kalorie.mezi = kalorie.mezi + "\nGlyk index: ";
                
                        elif cary==6:
                            kalorie.mezi = kalorie.mezi + "\nCholesterol: ";
                            
                        elif cary==7:
                            kalorie.mezi = kalorie.mezi + "\nVlaknina: ";
                            
                if cary == 0:
                    nazev = nazev + kalorie.rep1;
                elif cary == 1:
                    kj = kj + kalorie.rep1;
                
                    
                            
                            
                kalorie.mezi = kalorie.mezi + kalorie.rep1;
                
                if kalorie.rep1 == "\n":   #pokud dojdes na konec radku
                        kalorie.mezi = kalorie.mezi + "\n********************************\n\n"
                        cary = 0;
                        kde = kde + 1;
                        rep = indexs[kde];
                
                        kalorie.kalk.append([nazev, kj]);
                        nazev = "";
                        kj = "";
                        
                
              
            label = gtk.Label();
            win1.set_title("Vysledek vyhledavani");

            
            area = hildon.PannableArea();
            area.add_with_viewport(label);
                    
            win1.add(area);
            
            
            
            menu = hildon.AppMenu();
            win1.set_app_menu(menu);
            
            pridej = gtk.Button("Pridat do kalkulacky")

            pridej.connect("clicked", self.pridej_selector, kalorie.kalk);
            
            menu.append(pridej)
            
            
            

            label.set_text(kalorie.mezi);
            win1.show_all();
            menu.show_all();
             
        
    

    
    
    def __init__(self, widget):
        kalorie.kalk = [];
        kalorie.selectn = [];
        
        win4=hildon.StackableWindow();
        vb3=gtk.VBox();
        win4.add(vb3);
    
        
        vyhlb= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Vyhledavani");
        vyhlb.connect("clicked", self.vyhlkalgui);
        vb3.pack_start(vyhlb, expand=False);
        
        kalkb= hildon.Button(gtk.HILDON_SIZE_FINGER_HEIGHT,hildon.BUTTON_ARRANGEMENT_VERTICAL,"Kalkulacka");
        kalkb.connect("clicked", self.kalkulacka);
        vb3.pack_start(kalkb, expand=False);
    
        win4.show_all();